package cn.gson.financial.controller;

import cn.gson.financial.base.BaseCrudController;
import cn.gson.financial.kernel.constans.ComprehensiveParamesConstans;
import cn.gson.financial.kernel.controller.JsonResult;
import cn.gson.financial.kernel.dao.ComprehensiveParamsDao;
import cn.gson.financial.kernel.dao.ExportFileDao;
import cn.gson.financial.kernel.excelexport.*;
import cn.gson.financial.kernel.model.entity.*;
import cn.gson.financial.kernel.model.mapper.VoucherDetailsMapper;
import cn.gson.financial.kernel.model.vo.*;
import cn.gson.financial.kernel.service.*;
import cn.gson.financial.kernel.utils.*;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：ywh
 * @Date：2023/4/12 16:39
 * @Description：
 */
@RestController
@RequestMapping("/export")
public class ExportFileController extends BaseCrudController<ReportTemplateService, ReportTemplate>{

    @Autowired
    private AllSelectService allSelectService;
    @Autowired
    private ExportFileDao exportFileDao;
    @Autowired
    private ComprehensiveParamsDao comprehensiveParamsDao;
    @Autowired
    private OssService ossService;
    @Autowired
    private ExportFileService exportFileService;
    @Autowired
    private VoucherDetailsMapper detailsMapper;
    @Autowired
    private ReportTemplateController reportTemplateController;
    @Autowired
    private AccountSetsController accountSetsController;
    @Autowired
    private ReportBottomTableService reportBottomTableService;

    private String uploadOldAccount(MultipartFile multipartFile){
        String filename =multipartFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".")+1);

        if (suffix.equals("xls") || suffix.equals("xlsx")){
            String fileId = ossService.uploadFile(multipartFile);
//            String fileId = "test";
            String fileIdName = "{\"filename\":" + "\"" + filename + "\"" +","  + "\"fileId\":" + "\"" + fileId + "\"}";
            return fileIdName;

        }else {
            return "-1";
        }
    }


    private  String checkExcel(MultipartFile file ,String code){
        try {
            String content = comprehensiveParamsDao.queryDefaultContent(code);

            List list = Arrays.asList(JSONArray.parseArray(content).toArray());
            InputStream inputStream  =file.getInputStream();
            Workbook workbook;
            if (file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")){
                workbook = new HSSFWorkbook(inputStream);
            }else {
                workbook = new XSSFWorkbook(inputStream);
            }
            Sheet sheetAt = workbook.getSheetAt(0);
            Row row = sheetAt.getRow(0);
            int physicalNumberOfCells = row.getPhysicalNumberOfCells();//excel第一行的物理单元格数量
            if (physicalNumberOfCells < list.size()){
                System.out.println("assx");
//                return JsonResult.failure("期初Excel内容格式错误，请下载模板，在模板中填写数据后上传！");
                return "-1";
            }else {
                for (int i = 0; i < list.size(); i++) {
                    String columnIndex = JsonStringUtil.JsonStringGetValueByKey(String.valueOf(list.get(i)), "columnIndex");
                    String headContent = JsonStringUtil.JsonStringGetValueByKey(String.valueOf(list.get(i)), "content");
                    String cellValue = row.getCell(Integer.parseInt(columnIndex)).getStringCellValue();
                    if (!headContent.equals(cellValue)){
                        System.out.println("Excel中的 "+cellValue+" 与数据库中的 "+headContent +" 不一致");
//                        return JsonResult.failure("期初Excel内容格式错误，请下载模板，在模板中填写数据后上传！");
                        return "-1";
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "200";
    }



    //旧账导入
    @PostMapping("/oldAccountImport")
    public JsonResult oldAccountImport(OldAccountImportBean oldAccountImportBean) {
        if (oldAccountImportBean.getOpeningFile() == null && oldAccountImportBean.getVoucherFile()==null){
            return JsonResult.successful("您上传的文件为空，请选择文件后再去导入！");
        }

        //如果选择导入的是新账套;第一期不做
//        if (oldAccountImportBean.getIsNewAccount().equals("是")){
//            AccountSets accountSets = exportFileDao.createExportAccountSets(oldAccountImportBean);
//            accountSetsController.save(accountSets);
//        }

        String fileIdName = "";
        //期初导入
        if (oldAccountImportBean.getOpeningFile() != null){
            String openingFileIdName = this.uploadOldAccount(oldAccountImportBean.getOpeningFile());
            if (openingFileIdName.equals("-1")){
                return JsonResult.failure("你上传的文件格式错误，请先下载模板参考！");
            }
            //查看该excel中的格式是否为下载模板的格式；下面4行代码这期不做，下期可以打开注释
//            String checkExcelResult = this.checkExcel(oldAccountImportBean.getOpeningFile(), ComprehensiveParamesConstans.OLD_ACCOUNT_EXCEL_HEAD);
//            if (checkExcelResult.equals("-1")){
//                return JsonResult.failure("期初Excel内容格式错误，请下载模板，在模板中填写数据后上传！");
//            }
            fileIdName += openingFileIdName + ",";
        }
        //凭证导入
        if (oldAccountImportBean.getVoucherFile() != null){
            String voucherFileIdName = this.uploadOldAccount(oldAccountImportBean.getVoucherFile());
            if (voucherFileIdName.equals("-1")){
                return JsonResult.failure("你上传的文件格式错误，请先下载模板参考！");
            }
            fileIdName += voucherFileIdName + ",";
        }
        fileIdName = fileIdName.substring(0, fileIdName.length() - 1);
        fileIdName = "[" +fileIdName + "]";
        oldAccountImportBean.setCreateTime(new Date());
        oldAccountImportBean.setFileIdName(fileIdName);
        return JsonResult.successful(exportFileService.oldAccountImport(oldAccountImportBean));
    }

    //旧账导入 下载模板
    @GetMapping("/oldAccountModel")
    public ResponseEntity<byte[]> oldAccountModel() throws UnsupportedEncodingException {
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.DOWN_LOAD_OLD_ACCOUNT_MODEL);
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        byte[] bytes = ossService.downLoadFile(fileId);
        String fileType = fileId.substring(fileId.lastIndexOf("."));
        String fileName = "fxy" + System.currentTimeMillis() +  fileType;
        String downFileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", downFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        return responseEntity;
    }

        //总账导出
    @GetMapping("/downloadLedgerToExcel")
    public void downloadLedgerToExcel(String companyName,Integer accountSetsId,String startTime, String endTime ,String startSubject,String endSubject,Integer startLevel,Integer endLevel,boolean isOpen,boolean showNumPrice, HttpServletResponse response) throws Exception {
        //相对于/accountBook/generalLedgerByParam(查询总账)，新增参数companyName(账套名字),accountSetsId(账套id)

        String date = this.geDate(startTime,endTime);
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_ALL_ACCOUNT_EXPORT);
        String showNumPriceContent= JsonStringUtil.JsonStringGetValueByKey(content, String.valueOf(showNumPrice));
        String fileName = JsonStringUtil.JsonStringGetValueByKey(showNumPriceContent, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(showNumPriceContent, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(showNumPriceContent, "sheetName");
        ExcelProUtil excelProUtil = new ExcelProUtil();
        if (showNumPrice == true){


        }else {
            List<AllAccountExport> list = exportFileService.downloadLedgerToExcel(accountSetsId, startTime, endTime, startSubject, endSubject, startLevel, endLevel,isOpen,showNumPrice);
            String[] title = {"科目编码","科目名称","期间","摘要","借方金额","贷方金额","方向","余额"};
            byte[]  bytes = ossService.downLoadFile(fileId);
            InputStream inputStream = new ByteArrayInputStream(bytes);
            //处理sheet表
            Workbook delWithWorkbook = exportFileService.allAccountExport(inputStream,title.length,companyName,sheetName,date);
            Workbook workbook = excelProUtil.excelExport(list, sheetName, title, delWithWorkbook,true);//写入数据
            excelProUtil.excelResponse(workbook,fileName,response);//导出
            inputStream.close();
        }

    }

    //明细账导出
    @PostMapping("/downloadSubsidiaryToExcel")
    public void downloadSubsidiaryToExcel(@RequestBody AccountBookVo vo,HttpServletResponse response) throws Exception {
        //相对于/accountBook/supdetails(查询明细账)，新增参数accountSetsId（账号id），companyName（账套名字）
        System.out.println(vo);
        List<SubLedger> subLedgerList = exportFileService.downloadSubsidiaryToExcel(vo);
        ExcelProUtil excelProUtil = new ExcelProUtil();
        String[] title = {"日期","凭证字号","科目编码","科目名称","摘要","借方","贷方","方向","余额"};
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_SUB_LEDGER_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        byte[]  bytes = ossService.downLoadFile(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //处理sheet表
        Workbook delWithWorkbook = exportFileService.subLedgerExport(vo.getSubjectName(),inputStream,title.length,vo.getCompanyName(),sheetName,new SimpleDateFormat("yyyy-MM-dd").format(vo.getTimeList().get(0)));
        Workbook workbook = excelProUtil.excelExport(subLedgerList, sheetName, title, delWithWorkbook,true);//写入数据
        excelProUtil.excelResponse(workbook,fileName,response);//导出
        inputStream.close();
    }

    //科目余额导出
    @GetMapping("/downloadAccountBalanceToExcel")
    public void downloadAccountBalanceToExcel(String companyName,String startTime,String endTime ,String startSubject, String endSubject, Integer startLevel, Integer endLevel,Integer accountSetsId,Boolean showNumPrice,boolean isOpen,HttpServletResponse response) throws Exception {

        String date = this.geDate(startTime,endTime);
        List<AccountBalanceExport> accountBalanceExportList = exportFileService.downloadAccountBalanceToExcel(companyName,startTime, endTime, startSubject, endSubject, startLevel, endLevel, accountSetsId, showNumPrice,isOpen);

        ExcelProUtil excelProUtil = new ExcelProUtil();
        String[] title = {"科目编码","科目名称","借方","贷方","借方","贷方","借方","贷方"};
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_ACCOUNT_BALANCE_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        String writeTitleIndex = JsonStringUtil.JsonStringGetValueByKey(content, "writeTitleIndex");//需要修改表头；编制单位：  pp杂货铺	2023年4月至2023年4月  单位：元

        byte[]  bytes = ossService.downLoadFile(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //处理sheet表
        Workbook delWithWorkbook = exportFileService.accountBalanceExport(inputStream,title.length,companyName,sheetName,date,Integer.valueOf(writeTitleIndex));
        Workbook workbook = excelProUtil.excelExport(accountBalanceExportList, sheetName, title, delWithWorkbook,false);//写入数据
        excelProUtil.excelResponse(workbook,fileName,response);//导出
        inputStream.close();
    }

    private String geDate(String startTime, String endTime) throws ParseException {
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月");
        String startTimeDate = simpleDateFormat2.format(simpleDateFormat1.parse(startTime));
        String endTimeDate = simpleDateFormat2.format(simpleDateFormat1.parse(endTime));
        String date =startTimeDate + "至" +  endTimeDate;
        return date;
    }

    //时序账导出
    @GetMapping("/downloadChronologicalAccountToExcel")
//    public void downloadChronologicalAccountToExcel(Integer accsetsId,String sTime,String eTime,String sWordCode,String eWordCode,String word,String summary,String subjectCode,String sMoney,String eMoney,Integer sort,HttpServletResponse response) throws Exception {
    public void downloadChronologicalAccountToExcel(@RequestParam("subjectCode")String subjectCode, HttpServletResponse response) throws Exception {
        //相对于/voucher/getChronologicalAccount?accsetsId(查询时序账)
        //测试数据
        int accsetsId=2;
        String sTime = "";
        String eTime ="";
        String sWordCode = "";
        String eWordCode = "";
        String word="";
        String summary="";
//        String subjectCode="1001006";//100100301;1122
        String sMoney="";
        String eMoney="";
        Integer sort=1;

        String sSubjectCode=subjectCode;
        String eSubjectCode="";
        if(BaseUtil.checkValueIsNull(subjectCode).contains("-")){
            String[] sry = subjectCode.split("-");
            sSubjectCode = sry[0];
            eSubjectCode = sry[1];
        }

        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_CHRONOLOGICAL_ACCOUNT_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        String columnIndex = JsonStringUtil.JsonStringGetValueByKey(content, "columnIndex");
        List<List<Object>> lists = exportFileService.downloadChronologicalAccountToExcel(accsetsId, sTime, eTime, sWordCode, eWordCode, word, summary, sSubjectCode, eSubjectCode, sMoney, eMoney, sort,columnIndex);
        ExcelUtils.export(response,fileName,sheetName,lists);

    }

    //凭证导出
    @PostMapping("/voucherExport")
    public void voucherExport(@RequestBody VoucherSelectVo vo,HttpServletResponse response){
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_VOUCHER_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        String columnIndex = JsonStringUtil.JsonStringGetValueByKey(content, "columnIndex");
        List<List<Object>> lists = exportFileService.voucherExport(vo,columnIndex,this.accountSetsId);
        ExcelUtils.export(response,fileName,sheetName,lists);
    }

    //现金流量表导出
    @PostMapping("/downloadCashFlowToExcel")
    public void downloadCashFlowToExcel(@RequestBody ReportBMXMVo reportBMXMVo,HttpServletResponse response) throws Exception {
        //相对于/accountBook/details(查询明细账)，新增参数companyName（账套名字）
        List<BottomTableVo> bottomTableVos = reportBottomTableService.viewG(this.accountSetsId,reportBMXMVo.getReportTemlateId(), reportBMXMVo.getSTime().substring(0,7), reportBMXMVo.getETime().substring(0,7));
        Map<String, BottomTableVo> bottomTableVoMap = bottomTableVos.stream().collect(Collectors.toMap(BottomTableVo::getTemplateId, bottomTableVo -> bottomTableVo));
        QueryWrapper qw = Wrappers.query();
        qw.eq("id", reportBMXMVo.getReportTemlateId());
        this.setQwAccountSetsId(qw);
        ReportTemplate allData = service.getOne(qw);
        List<CashFlowExport> cashFlowExportList = exportFileService.downloadCashFlowToExcel(allData,bottomTableVoMap);

        ExcelProUtil excelProUtil = new ExcelProUtil();
        String[] title = {"项目","行次","本年累计金额","本期金额"};
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_CASH_FLOW_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        byte[]  bytes = ossService.downLoadFile(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String date = "";
        if (reportBMXMVo.getETime() == null || reportBMXMVo.getETime().equals("")){
            date = new SimpleDateFormat("yyyy年MM月dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
        }else {
            int season = TimeUtil.getSeason(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getETime()));
            date = new SimpleDateFormat("yyyy年第").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getETime())) + season+"季度";
        }
        //处理sheet表
        Workbook delWithWorkbook = exportFileService.cashFlowExport(inputStream,title.length,reportBMXMVo.getCompanyName(),sheetName,date);
        Workbook workbook = excelProUtil.excelExport(cashFlowExportList, sheetName, title, delWithWorkbook,true);//写入数据
        excelProUtil.excelResponse(workbook,fileName,response);//导出
        inputStream.close();
    }


    //利润表导出
    @PostMapping("/downloadProfitToExcel")
    public void downloadProfitToExcel(@RequestBody ReportBMXMVo reportBMXMVo,HttpServletResponse response) throws Exception {

        Map<Integer, ReportDataVo> integerReportDataVoMap = service.viewReport(reportBMXMVo.getAccountSetsId(), reportBMXMVo.getReportTemlateId(), reportBMXMVo.getSTime(), reportBMXMVo.getETime());
        QueryWrapper qw = Wrappers.query();
        qw.eq("id", reportBMXMVo.getReportTemlateId());
        this.setQwAccountSetsId(qw);
        ReportTemplate allData = service.getOne(qw);
        List<ProfitExport> profitExportList = exportFileService.downloadProfitToExcel(allData,integerReportDataVoMap);

        ExcelProUtil excelProUtil = new ExcelProUtil();
        String[] title = {"项目","行次","本年累计金额","本期金额"};
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_PROFIT_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        byte[]  bytes = ossService.downLoadFile(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //处理sheet表，使用的现金流量表的处理，因为他们的字段之类的的全一样
        String companyName = reportBMXMVo.getCompanyName();

        String date = "";
        String eTime = reportBMXMVo.getETime();
        if (eTime == null || eTime.equals("")){
            date = new SimpleDateFormat("yyyy年MM月dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
        }else {
            int season = TimeUtil.getSeason(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
            date = new SimpleDateFormat("yyyy年第").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime())) + season+"季度";
        }
        Workbook delWithWorkbook = exportFileService.cashFlowExport(inputStream,title.length,companyName,sheetName,date);
        Workbook workbook = excelProUtil.excelExport(profitExportList, sheetName, title, delWithWorkbook,true);//写入数据
        excelProUtil.excelResponse(workbook,fileName,response);//导出
        inputStream.close();
    }

    //项目/部门利润表导出
    @GetMapping("/downloadProjectProfitToExcel")
//    public void downloadProjectProfitToExcel(@RequestBody ReportBMXMVo vo,HttpServletResponse response) throws Exception {
    public void downloadProjectProfitToExcel(HttpServletResponse response) throws Exception {
        //相对于/report/template/viewsReport(查询明细账)，新增参数companyName（账套名字）
        //测试数据
        ReportBMXMVo reportBMXMVo = new ReportBMXMVo();
        reportBMXMVo.setAccountSetsId(67);
        reportBMXMVo.setReportTemlateId(22L);
        reportBMXMVo.setSTime("2022-01-01");
        reportBMXMVo.setETime("2023-04-30");
        reportBMXMVo.setCompanyName("测试账套");
        reportBMXMVo.setIds(Arrays.asList(new Integer[]{12, 13}));

        List<DepartmentOrProjectVO> views = reportTemplateController.getViews(reportBMXMVo);//本年累计金额
        QueryWrapper qw = Wrappers.query();
        qw.eq("id", reportBMXMVo.getReportTemlateId());
        this.setQwAccountSetsId(qw);
        ReportTemplate allData = service.getOne(qw);
        List<ProfitExport> profitExportList = exportFileService.downloadProjectProfitToExcel(allData,views);

        ExcelProUtil excelProUtil = new ExcelProUtil();
        String[] title = {"项目","行次","本年累计金额","本期金额"};
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_PROFIT_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        byte[]  bytes = ossService.downLoadFile(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //处理sheet表，使用的现金流量表的处理，因为他们的字段之类的的全一样
        String companyName = reportBMXMVo.getCompanyName();

        String date = "";
        String eTime = reportBMXMVo.getETime();
        if (eTime == null || eTime.equals("")){
            date = new SimpleDateFormat("yyyy年MM月dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
        }else {
            int season = TimeUtil.getSeason(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
            date = new SimpleDateFormat("yyyy年第").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime())) + season+"季度";
        }
        Workbook delWithWorkbook = exportFileService.cashFlowExport(inputStream,title.length,companyName,sheetName,date);
        Workbook workbook = excelProUtil.excelExport(profitExportList, sheetName, title, delWithWorkbook,true);//写入数据
        excelProUtil.excelResponse(workbook,fileName,response);//导出
        inputStream.close();
    }


    //资产负债表导出
    @PostMapping("/downloadAssetsLiabilitiesToExcel")
    public void downloadAssetsLiabilitiesToExcel(@RequestBody ReportBMXMVo reportBMXMVo,HttpServletResponse response) throws Exception {
        //相对于/report/template/viewsReport，新增参数companyName（账套名字）
        Map<Integer, ReportDataVo> integerReportDataVoMap = service.viewReport(reportBMXMVo.getAccountSetsId(), reportBMXMVo.getReportTemlateId(), reportBMXMVo.getSTime(), reportBMXMVo.getETime());
        QueryWrapper qw = Wrappers.query();
        qw.eq("id", reportBMXMVo.getReportTemlateId());
        this.setQwAccountSetsId(qw);
        ReportTemplate allData = service.getOne(qw);
        List<AssetsLiabilitiesExport> assetsLiabilitiesExportList = exportFileService.downloadAssetsLiabilitiesToExcel(allData,integerReportDataVoMap);
        ExcelProUtil excelProUtil = new ExcelProUtil();
        String[] title = {"资产","行次","期末余额","年初余额","负债和所有者权益","行次","期末余额","年初余额"};
        String content = comprehensiveParamsDao.queryDefaultContent(ComprehensiveParamesConstans.EXPORT_ASSETS_LIABILITIES_EXPORT);
        String fileName = JsonStringUtil.JsonStringGetValueByKey(content, "fileName");
        String fileId = JsonStringUtil.JsonStringGetValueByKey(content, "fileId");
        String sheetName = JsonStringUtil.JsonStringGetValueByKey(content, "sheetName");
        byte[]  bytes = ossService.downLoadFile(fileId);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        //处理sheet表，使用的现金流量表的处理，因为他们的字段之类的的全一样
        String companyName = reportBMXMVo.getCompanyName();

        String date = "";
        String eTime = reportBMXMVo.getETime();
        if (eTime == null || eTime.equals("")){
            date = new SimpleDateFormat("yyyy年MM月dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
        }else {
            int season = TimeUtil.getSeason(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime()));
            date = new SimpleDateFormat("yyyy年第").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportBMXMVo.getSTime())) + season+"季度";
        }
        Workbook delWithWorkbook = exportFileService.assetsLiabilitiesExporrt(inputStream,title.length,companyName,sheetName,date);

        assetsLiabilitiesExportList.forEach(System.out::println);
        Workbook workbook = excelProUtil.excelExport(assetsLiabilitiesExportList, sheetName, title, delWithWorkbook,true);//写入数据
        excelProUtil.excelResponse(workbook,fileName,response);//导出
        inputStream.close();
    }
}
